<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="chat-header">
      <view class="header-left" @click="showConversationList">
        <uni-icons type="list" size="22" color="#333"></uni-icons>
      </view>
      <view class="header-title">{{ pageTitle }}</view>
      <view class="header-right" @click="startNewConversation">
        <uni-icons type="compose" size="22" color="#333"></uni-icons>
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-content" 
      scroll-y 
      :scroll-into-view="scrollToView"
      scroll-with-animation
    >
      <!-- 智能体开场白 -->
      <view v-if="showWelcome" class="welcome-section">
        <view class="welcome-message">
          <view class="welcome-avatar">
            <text class="avatar-text">小星</text>
          </view>
          <view class="welcome-content">
            <view class="welcome-text">{{ openingStatement }}</view>
          </view>
        </view>
        <view class="welcome-tips">
          <text>有什么问题可以随时问我哦~</text>
        </view>
      </view>

      <!-- 聊天消息列表 -->
      <view v-if="showMessages" class="messages-container">
        <view 
          v-for="(message, index) in messages" 
          :key="message.id || index"
          :id="`message-${index}`"
          class="message-wrapper"
          :class="{
            'user-message': message.from === 'user',
            'ai-message': message.from === 'ai'
          }"
        >
          <!-- 头像 -->
          <view class="message-avatar">
            <text class="avatar-text">{{ message.from === 'user' ? '我' : '小星' }}</text>
          </view>
          
          <!-- 消息内容 -->
          <view class="message-content">
            <!-- 文本消息 -->
            <view class="text-message" v-if="message.type === 'text' || !message.type">
              {{ message.content }}
            </view>
            

          </view>
        </view>

        <!-- 正在输入提示 -->
        <view v-if="isTyping" class="typing-wrapper">
          <view class="message-avatar">
            <text class="avatar-text">小星</text>
          </view>
          <view class="typing-content">
            <span class="typing-text">大脑疯狂运转中，指尖在键盘上跳踢踏舞，专属回复正在加急酿造ing<span class="typing-dots">
              <span class="typing-dot"></span>
              <span class="typing-dot"></span>
              <span class="typing-dot"></span>
            </span></span>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <!-- 输入框 -->
        <input 
          class="message-input" 
          v-model="inputContent"
          type="text"
          placeholder="请输入消息..."
          @confirm="sendMessage"
          :disabled="isTyping"
          @focus="onInputFocus"
        />
        
        <!-- 发送按钮 -->
        <button 
          class="send-button" 
          @click="sendMessage"
          :disabled="!inputContent.trim() || isTyping"
        >
          发送
        </button>
      </view>
    </view>
  </view>
    

</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
import chatApi from '../../api/chat'
import { storageAsync } from '../../utils/index'
const { sendStreamingChatMessage } = chatApi

export default {
  name: 'ChatMain',
  components: {
    'uni-icons': uniIcons
  },
  // uni-app生命周期钩子
  onShow() {
    this.handlePageShow()
  },
  setup() {
    const router = useRouter()
    
    // 页面状态
    const pageTitle = ref('奇思妙想茶话会')
    const showWelcome = ref(true)
    const showMessages = ref(false)
    const scrollToView = ref('')
    
    // 智能体参数
    const openingStatement = ref('你好呀！我是挚友小星，有什么不懂的或者烦心事可以和我讲一讲哦，我会尽我所能帮解决问题')
    
    // 对话数据
    const messages = ref([])
    const conversationId = ref('')
    const inputContent = ref('')
    const isTyping = ref(false)
    

    
    // 监听页面显示事件（适用于tabBar页面切换）
    const handlePageShow = () => {
      console.log('===== 页面显示事件触发 =====')
      // 每次页面显示时都调用loadConversationFromParams函数
      // 这样可以确保从会话列表切换到chat页面时能够正确加载会话内容
      loadConversationFromParams()
    }


    
    // 加载会话历史消息
    const loadConversationHistory = async (targetConversationId) => {
      try {
        console.log('加载会话历史消息:', targetConversationId)
        // 显示加载状态
        isTyping.value = true
        console.log('===== loadConversationHistory函数开始执行 =====')
        console.log('传入的targetConversationId参数:', targetConversationId)
        
        // 首先尝试从本地存储获取预加载的消息
        console.log('尝试从本地存储获取预加载消息...')
        const preloadedMessagesKey = `preloadedMessages_${targetConversationId}`;
        const preloadedMessages = uni.getStorageSync(preloadedMessagesKey);
        console.log('获取到的预加载消息:', preloadedMessages)
        console.log('预加载消息是否存在:', !!preloadedMessages)
        
        // 如果有预加载的消息，直接使用并返回
        if (preloadedMessages && Array.isArray(preloadedMessages) && preloadedMessages.length > 0) {
          console.log('使用预加载的消息数据')
          
          // 处理预加载的消息格式
          const transformedMessages = [];
          preloadedMessages.forEach(msg => {
            // 添加用户消息（如果有query）
            if (msg.query && msg.query.trim()) {
              transformedMessages.push({
                id: `user-${msg.id || Date.now()}`,
                from: 'user',
                content: msg.query,
                type: 'text',
                timestamp: msg.created_at || msg.timestamp || Date.now(),
                message_id: msg.message_id || msg.id
              });
            }
            
            // 添加AI回复消息（如果有answer）
            if (msg.answer && msg.answer.trim()) {
              transformedMessages.push({
                id: `ai-${msg.id || Date.now()}`,
                from: 'ai',
                content: msg.answer,
                type: 'text',
                timestamp: msg.created_at || msg.timestamp || Date.now(),
                message_id: msg.message_id || msg.id
              });
            }
          });
          
          // 先清空现有消息，确保不会有旧消息残留
          messages.value = [];
          console.log('清空现有消息数组，准备加载新消息')
          
          // 强制DOM更新，确保空消息状态被渲染
          await nextTick();
          console.log('DOM已更新为空消息状态')
          
          // 设置新消息
          messages.value = transformedMessages;
          console.log('转换后的消息数量:', messages.value.length);
          
          // 清除预加载的消息，避免下次重复使用
          uni.removeStorageSync(preloadedMessagesKey);
          console.log('已清除预加载消息缓存')
          
          // 再次强制DOM更新，确保新消息被渲染
          await nextTick();
          console.log('DOM已更新，新消息已渲染')
          
          // 滚动到底部
          if (messages.value.length > 0) {
            scrollToView.value = `message-${messages.value.length - 1}`;
            console.log('已设置滚动位置到底部')
          }
          
          // 最后再进行一次DOM更新，确保滚动生效
          await nextTick();
          
          // 重置加载状态
          isTyping.value = false;
          
          return; // 直接返回，避免继续调用API
        }
        
        console.log('没有找到预加载的消息，将从API获取')
        
        // 从本地存储获取用户信息
        console.log('开始从本地存储获取用户信息...')
        let userInfo = uni.getStorageSync('userInfo') || {};
        console.log('获取到的用户信息:', userInfo)
        console.log('用户信息类型:', typeof userInfo)
        
        // 确保userInfo是对象
        if (typeof userInfo === 'string') {
          try {
            userInfo = JSON.parse(userInfo)
            console.log('解析后的用户信息:', userInfo)
          } catch (e) {
            console.error('用户信息格式错误:', e)
            userInfo = {}
          }
        }
        
        // 多种方式尝试获取用户名
        console.log('开始提取用户名...')
        console.log('用户信息属性检查:', Object.keys(userInfo || {}))
        let username = ''
        if (userInfo && typeof userInfo === 'object') {
          console.log('用户信息有效，尝试提取用户名')
          // 尝试不同的属性名
          console.log('检查username属性:', userInfo.username)
          console.log('检查user属性:', userInfo.user)
          console.log('检查nickname属性:', userInfo.nickname)
          username = userInfo.username || userInfo.user || userInfo.nickname || ''
          // 如果属性存在但值为空，尝试从对象中直接获取
          if (!username && userInfo.hasOwnProperty('username')) {
            console.log('username属性存在但为空，尝试直接转换为字符串')
            username = String(userInfo.username)
          }
        }
        
        console.log('提取到的用户名:', username)
        console.log('用户名长度:', username.length)
        console.log('用户名是否为空:', !username || username.trim() === '')
        
        // 确保用户名存在，否则抛出错误
        console.log('===== 开始验证用户名 =====')
        console.log('用户名验证前:', { value: username, length: username.length, isEmpty: !username || username.trim() === '' })
        if (!username || username.trim() === '') {
          console.error('❌ 用户名验证失败：用户名不存在或为空')
          throw new Error('未找到登录用户信息，请先登录')
        }
        console.log('✅ 用户名验证成功')
        
        // 调用新的API获取会话历史
        console.log('===== 准备调用getConversationHistory API =====')
        console.log('会话ID:', targetConversationId)
        console.log('用户:', username)
        console.log('消息限制:', 20)
        
        let response;
        try {
          console.log('开始调用chatApi.getConversationHistory')
          response = await chatApi.getConversationHistory({
            conversation_id: targetConversationId,
            user: username,
            limit: 20
          })
          console.log('===== 成功获取API响应 =====')
          console.log('响应对象:', response)
          console.log('响应对象类型:', typeof response)
          console.log('响应对象属性:', Object.keys(response || {}))
          
          // 更新页面标题为对话主题
          if (response.title && response.title.trim()) {
            pageTitle.value = response.title.trim()
            console.log('已从API响应更新页面标题:', pageTitle.value)
          } else if (response.data && response.data.title && response.data.title.trim()) {
            pageTitle.value = response.data.title.trim()
            console.log('已从API响应data对象更新页面标题:', pageTitle.value)
          }
        } catch (apiError) {
          console.error('===== API调用异常捕获 =====')
          console.error('API错误类型:', apiError?.constructor?.name || 'Unknown')
          console.error('API错误详情:', apiError?.message || 'No error message')
          throw apiError
        }
        
        // 处理响应数据，转换为消息格式
        if (response && response.messages && Array.isArray(response.messages)) {
          console.log('响应包含messages数组，长度:', response.messages.length)
          
          // 用于存储转换后的消息
          const transformedMessages = []
          
          // 遍历响应中的消息
          response.messages.forEach(msg => {
            // 添加用户消息（如果有query）
            if (msg.query && msg.query.trim()) {
              transformedMessages.push({
                id: `user-${msg.id || Date.now()}`,
                from: 'user',
                content: msg.query,
                type: 'text',
                timestamp: msg.created_at || Date.now(),
                message_id: msg.message_id || msg.id
              })
            }
            
            // 添加AI回复消息（如果有answer）
            if (msg.answer && msg.answer.trim()) {
              transformedMessages.push({
                id: `ai-${msg.id || Date.now()}`,
                from: 'ai',
                content: msg.answer,
                type: 'text',
                timestamp: msg.created_at || Date.now(),
                message_id: msg.message_id || msg.id
              })
            }
          })
          
          // 先清空现有消息，确保不会有旧消息残留
          messages.value = [];
          console.log('清空现有消息数组，准备加载API返回的消息')
          
          // 强制DOM更新，确保空消息状态被渲染
          await nextTick();
          console.log('DOM已更新为空消息状态')
          
          // 设置新消息
          messages.value = transformedMessages
          console.log('转换后的消息数量:', messages.value.length)
          
          // 强制DOM更新，确保新消息被渲染
          await nextTick();
          console.log('DOM已更新，API返回的新消息已渲染')
        } else {
          console.log('响应不包含有效的messages数组，设置为空数组')
          messages.value = []
        }
        
        await nextTick()
        if (messages.value.length > 0) {
          scrollToView.value = `message-${messages.value.length - 1}`
        }
      } catch (error) {
        console.error('===== 加载历史消息错误捕获 =====')
        console.error('错误类型:', error?.constructor?.name || 'Unknown')
        console.error('错误对象:', error)
        console.error('错误详情:', JSON.stringify(error, Object.getOwnPropertyNames(error || {})))
        
        // 错误处理：显示提示信息
        let errorMessage = '加载历史消息失败'
        if (error?.message?.includes('未找到登录用户信息')) {
          errorMessage = '请先登录后再查看会话'
        } else if (error?.message) {
          errorMessage = error.message
        }
        
        uni.showToast({
          title: errorMessage.length > 20 ? '加载失败，请重试' : errorMessage,
          icon: 'none',
          duration: 2000
        })
        
        // 使用模拟数据
        messages.value = [
          {
            id: `user-${Date.now() - 3600000}`,
            from: 'user',
            content: '你好，最近怎么样？',
            type: 'text',
            timestamp: Date.now() - 3600000
          },
          {
            id: `ai-${Date.now() - 3590000}`,
            from: 'ai',
            content: '我很好！很高兴收到你的消息。今天有什么可以帮助你的吗？',
            type: 'text',
            timestamp: Date.now() - 3590000
          }
        ]
        await nextTick()
        if (messages.value.length > 0) {
          scrollToView.value = `message-${messages.value.length - 1}`
        }
      } finally {
        // 确保加载状态被重置
        isTyping.value = false;
        console.log('===== loadConversationHistory函数执行完成 =====')
      }
    }

    // 开始新聊天
    const startNewConversation = () => {
      console.log('开启新聊天')
      // 重置聊天状态
      conversationId.value = ''
      messages.value = []
      showWelcome.value = true
      showMessages.value = false
      uploadedFiles.value = []
      inputContent.value = ''
  pageTitle.value = '奇思妙想茶话会'
  // 重新获取智能体参数（可选，确保开场白最新）
      fetchAgentParameters()
    }

    // 发送消息
    const sendMessage = async () => {
      // 验证输入内容
      if (!inputContent.value.trim() && uploadedFiles.value.length === 0) {
        return
      }
      
      // 获取输入内容
      const content = inputContent.value.trim()
      
      // 切换到消息显示模式
      if (showWelcome.value) {
        showWelcome.value = false
        showMessages.value = true
      }
      
      // 添加用户消息
      const userMessage = {
        id: `user-${Date.now()}`,
        from: 'user',
        content: content,
        type: 'text',
        timestamp: Date.now()
      }
      messages.value.push(userMessage)
      
      // 清空输入和上传文件
      inputContent.value = ''
      
      // 滚动到底部
      await nextTick()
      scrollToView.value = `message-${messages.value.length - 1}`
      
      // 显示输入状态
      isTyping.value = true
      
      try {
        // 从本地存储获取用户信息
        const userInfo = await storageAsync.get('userInfo') || {};
        const username = userInfo.username || 'anonymous'; // 默认为anonymous，以防没有用户信息
        
        // 准备发送的数据
        const sendData = {
          user: username,
          conversation_id: conversationId.value || '', // 留空会自动创建新会话
          query: content,
          inputs: {},
          auto_generate_name: true,
          response_mode: 'streaming'
        }
        
        console.log('发送消息数据:', sendData)
        
        // 准备AI消息对象，但暂时不添加到消息列表
        // 我们会在收到第一个数据块时再添加，避免显示空的白色框
        let aiMessageIndex = -1
        let aiMessage = {
          id: `ai-${Date.now()}`,
          from: 'ai',
          content: '',
          type: 'text',
          timestamp: Date.now()
        }
        
        // 处理每个数据块的回调函数
        const onChunk = async (chunk) => {
          try {
            console.log('收到数据块:', chunk)
            
            // 更新会话ID
            if (chunk.conversation_id && !conversationId.value) {
              conversationId.value = chunk.conversation_id
            }
            
            // 更新AI回复内容
            if (chunk.data && chunk.data.outputs && chunk.data.outputs.answer) {
              // 如果是第一个数据块，先添加AI消息到列表
              if (aiMessageIndex === -1) {
                aiMessageIndex = messages.value.length
                aiMessage.content = chunk.data.outputs.answer
                messages.value.push(aiMessage)
              } else {
                // 更新现有消息内容
                messages.value[aiMessageIndex].content = chunk.data.outputs.answer
              }
              
              // 滚动到底部
              await nextTick()
              scrollToView.value = `message-${messages.value.length - 1}`
            }
          } catch (error) {
            console.error('处理数据块失败:', error)
          }
        }
        
        // 完成流式响应的回调函数
        const onComplete = async (response) => {
          console.log('流式响应完成:', response)
          
          // 更新会话ID
          if (response.conversation_id) {
            conversationId.value = response.conversation_id
          }
          
          // 确保最终内容正确更新
          if (response.data && response.data.outputs && response.data.outputs.answer) {
            messages.value[aiMessageIndex].content = response.data.outputs.answer
          }
          
          // 更新页面标题为对话主题
          if (response.title && response.title.trim()) {
            pageTitle.value = response.title.trim()
          } else if (response.data && response.data.title && response.data.title.trim()) {
            pageTitle.value = response.data.title.trim()
          }
          
          // 清除正在输入状态
          isTyping.value = false
          
          // 滚动到底部
          await nextTick()
          scrollToView.value = `message-${messages.value.length - 1}`
        }
        
        // 错误处理回调函数
        const onError = (error) => {
          console.error('流式响应错误:', error)
          isTyping.value = false
          
          // 显示错误消息
          uni.showToast({
            title: '接收消息失败，请重试',
            icon: 'none',
            duration: 2000
          })
          
          // 更新AI消息为错误提示
          messages.value[aiMessageIndex].content = '抱歉，我暂时无法回复您的消息。请稍后再试。'
        }
        
        // 调用流式API发送消息
        await sendStreamingChatMessage(sendData, onChunk, onComplete, onError)
        
      } catch (error) {
        console.error('发送消息失败:', error)
        // 错误处理：显示错误消息
        uni.showToast({
          title: '发送消息失败，请重试',
          icon: 'none',
          duration: 2000
        })
        
        // 设置AI消息为错误提示
        if (!isTyping.value) {
          const aiMessage = {
            id: `ai-${Date.now()}`,
            from: 'ai',
            content: '抱歉，我暂时无法回复您的消息。请稍后再试。',
            type: 'text',
            timestamp: Date.now()
          }
          messages.value.push(aiMessage)
          
          await nextTick()
          scrollToView.value = `message-${messages.value.length - 1}`
        }
        
        isTyping.value = false
      } finally {
        // 确保清除正在输入状态
        setTimeout(() => {
          isTyping.value = false
        }, 1000)
      }
    }



    // 输入框聚焦
    const onInputFocus = () => {
      if (showWelcome.value) {
        showWelcome.value = false
        showMessages.value = true
      }
    }

    // 获取智能体参数
    const fetchAgentParameters = async () => {
      try {
        const response = await chatApi.getAgentParameters()
        if (response && response.opening_statement) {
          openingStatement.value = response.opening_statement
        }
        console.log('智能体参数获取成功:', response)
      } catch (error) {
        console.error('获取智能体参数失败:', error)
        // 使用默认开场白作为备选
        openingStatement.value = '你好呀！我是挚友小星，有什么不懂的或者烦心事可以和我讲一讲哦，我会尽我所能帮解决问题'
      }
    }

    // 显示对话列表（跳转到对话列表页面）
    const showConversationList = () => {
      console.log('跳转到对话列表页面')
      uni.navigateTo({ url: '/pages/chat/conversationList' })
    }
    
    // 从对话列表返回时根据URL参数和本地存储加载对应对话
    const loadConversationFromParams = async () => {
      console.log('===== 开始执行loadConversationFromParams =====')
      try {
        // 从多个来源获取conversation_id
        let selectedConversationId = ''
        
        // 来源1: 尝试从URL参数中获取
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const options = currentPage.options || {}
        
        if (options.conversation_id) {
          selectedConversationId = options.conversation_id
          console.log('===== 从URL参数获取会话ID =====', selectedConversationId)
        } else {
          console.log('===== URL参数中没有conversation_id =====')
          
          // 来源2: 尝试从临时存储中获取备用会话ID
          try {
            const tempId = uni.getStorageSync('tempConversationId')
            if (tempId) {
              selectedConversationId = tempId
              console.log('===== 从临时存储获取会话ID =====', selectedConversationId)
              // 获取后清除临时存储，避免重复使用
              uni.removeStorageSync('tempConversationId')
              console.log('===== 已清除临时存储中的会话ID =====')
            } else {
              console.log('===== 临时存储中也没有会话ID =====')
            }
          } catch (storageError) {
            console.error('===== 读取临时存储失败 =====', storageError)
          }
        }
        
       
        
        // 只有当conversationId不为空时才加载历史消息
        if (selectedConversationId) {
          // 验证会话ID格式（简单的UUID格式验证）
          const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
          if (!uuidPattern.test(selectedConversationId)) {
            console.warn('❌ 会话ID格式验证失败')
            console.warn('无效的会话ID:', selectedConversationId)
            console.warn('预期格式: UUID格式 (8-4-4-4-12)')
            return;
          }
          
          // 重要：在加载新会话前清空消息数组，避免显示之前会话的消息
          console.log('清空消息数组，准备加载新会话消息')
          
          // 强制重置所有相关状态
          messages.value = []
          inputContent.value = ''
          
          console.log('已重置所有会话相关状态')
          
          // 强制DOM更新
          await nextTick()
          console.log('第一次DOM更新完成，消息数组已清空')
          
          // 额外的延迟确保DOM完全更新
          await new Promise(resolve => setTimeout(resolve, 50))
          
          // 设置会话ID状态
          conversationId.value = selectedConversationId
          console.log('已设置conversationId状态:', conversationId.value)
          
          // 暂时使用默认标题，后续会在加载历史消息时更新为实际对话主题
          pageTitle.value = '奇思妙想茶话会'
          console.log('已更新页面标题')
          
          // 切换到消息显示模式
          showWelcome.value = false
          showMessages.value = true
          console.log('已切换到消息显示模式:', { showWelcome: showWelcome.value, showMessages: showMessages.value })
          
          // 再次强制DOM更新
          await nextTick()
          console.log('第二次DOM更新完成')
          
          // 添加一个短暂的延迟，确保所有状态更新和DOM变化完全生效
          console.log('等待所有状态更新和DOM变化完全生效...')
          await new Promise(resolve => setTimeout(resolve, 100))
          
          // 加载对话历史
          console.log('===== 准备调用loadConversationHistory函数 =====')
          console.log('传入loadConversationHistory的参数:', selectedConversationId)
          
          try {
            console.log('===== 开始执行loadConversationHistory =====')
            await loadConversationHistory(selectedConversationId)
            console.log('✅ loadConversationHistory函数执行成功完成')
          } catch (loadError) {
            console.error('❌ loadConversationHistory函数执行异常')
            console.error('异常类型:', loadError?.constructor?.name || 'Unknown')
            console.error('异常消息:', loadError?.message || 'No error message')
            console.error('完整异常对象:', loadError)
          }
        } else {
          console.log('未提供会话ID，显示欢迎页面以开始新聊天')
          // 确保重置所有会话相关状态
          conversationId.value = '';
      messages.value = [];
      inputContent.value = '';
      showWelcome.value = true;
      showMessages.value = false;
      pageTitle.value = '奇思妙想茶话会';
        }
      } catch (error) {
        console.error('加载对话参数失败:', error)
      }
    }
    
    // 注册导航栏返回事件
    const registerBackHandler = () => {
      uni.addInterceptor('navigateBack', {
        invoke(e) {
          return true
        }
      })
    }
    
    // 生命周期
    onMounted(() => {
      console.log('聊天页面加载完成')
      // 加载智能体参数
      fetchAgentParameters()
      // 从URL参数加载对话
      loadConversationFromParams()
      // 注册返回事件处理
      registerBackHandler()
    })
    
    // 页面状态
    const onPageShow = () => {
      console.log('===== 页面显示生命周期触发 =====')
      handlePageShow()
    }

    return {
      // 页面状态
      pageTitle,
      showWelcome,
      showMessages,
      scrollToView,
      
      // 智能体参数
      openingStatement,
      
      // 聊天数据
      messages,
      inputContent,
      isTyping,

      
      // 方法
      showConversationList,
      startNewConversation,
      sendMessage,

      onInputFocus,
      handlePageShow,
      onPageShow
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.chat-header {
  height: 50px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left,
.header-right {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  flex: 1;
  text-align: center;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

/* 欢迎区域 */
.welcome-section {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 20px;
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.welcome-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #07c160 0%, #06b356 100%);
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  box-shadow: 0 4px 16px rgba(7, 193, 96, 0.3);
  animation: pulse 2s infinite;
  flex-shrink: 0;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 16px rgba(7, 193, 96, 0.3);
  }
  50% {
    box-shadow: 0 6px 24px rgba(7, 193, 96, 0.5);
  }
  100% {
    box-shadow: 0 4px 16px rgba(7, 193, 96, 0.3);
  }
}

.welcome-content {
  background-color: #fff;
  border-radius: 20px;
  padding: 20px 24px;
  max-width: 90%;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  word-wrap: break-word;
}

.welcome-text {
  color: #333;
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 0;
}

.welcome-tips {
  color: #999;
  font-size: 14px;
  background-color: #f5f5f5;
  padding: 8px 16px;
  border-radius: 16px;
  margin-top: 16px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #07c160;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  word-wrap: break-word;
}

/* 消息列表 */
.messages-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 0;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
  max-width: 100%;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 44px;
  border-radius: 50%;
  background-color: var(--primary-light);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: white;
  margin-right: 12px;
  box-shadow: 0 3px 8px rgba(255, 133, 162, 0.2);
  transition: all 0.3s ease-in-out;
  animation: pulse 3s ease-in-out infinite;
}

.user-message .message-avatar {
  margin-right: 0;
  margin-left: 12px;
  background-color: var(--secondary-color);
  color: #fff;
}

.message-content {
  max-width: 75%;
  word-wrap: break-word;
  line-height: 1.6;
}

.text-message {
  padding: 14px 18px;
  border-radius: 22px;
  font-size: 15px;
  position: relative;
  box-shadow: 0 3px 10px rgba(255, 133, 162, 0.1);
  transition: all 0.3s ease-in-out;
  animation: fadeInUp 0.3s ease-out;
}

.user-message .message-content .text-message {
  background-color: var(--secondary-color);
  color: #fff;
  border-top-right-radius: 8px;
  animation: fadeInUp 0.3s ease-out;
}

.ai-message .message-content .text-message {
  background-color: white;
  color: var(--text-primary);
  border-top-left-radius: 8px;
  border: 1px solid var(--border-color);
  animation: fadeInUp 0.3s ease-out;
}



/* 正在输入提示 */
.typing-wrapper {
  display: flex;
  align-items: center;
  margin-top: 16px;
  animation: fadeIn 0.3s ease-in-out;
}

.typing-content {
  background-color: white;
  padding: 12px 16px;
  border-radius: 22px;
  border-top-left-radius: 8px;
  box-shadow: 0 3px 10px rgba(255, 133, 162, 0.1);
  border: 1px solid var(--border-color);
}

.typing-dots {
  display: inline-flex;
  gap: 4px;
  margin: 0 2px;
  vertical-align: middle;
}

.typing-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: var(--primary-color);
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-dot:nth-child(1) { animation-delay: -0.32s; }
.typing-dot:nth-child(2) { animation-delay: -0.16s; }
.typing-dot:nth-child(3) { animation-delay: 0s; }

.typing-text {
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 500;
}

@keyframes typing {
  0%, 80%, 100% { 
    transform: scale(0);
    opacity: 0;
  }
  40% { 
    transform: scale(1);
    opacity: 1;
  }
}

/* 输入区域 */
.input-area {
  background-color: white;
  border-top: 1px solid var(--border-color);
  padding: 12px 16px;
  box-shadow: 0 -3px 15px rgba(255, 133, 162, 0.1);
  backdrop-filter: blur(10px);
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.message-input {
  flex: 1;
  height: 48px;
  background-color: var(--border-light);
  border: 2px solid var(--border-color);
  border-radius: 24px;
  padding: 0 20px;
  font-size: 15px;
  color: var(--text-primary);
  box-shadow: inset 0 2px 4px rgba(255, 133, 162, 0.05);
  transition: all 0.3s ease-in-out;
}

.message-input:focus {
  background-color: white;
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 4px rgba(255, 133, 162, 0.1);
}

.send-button {
  height: 48px;
  padding: 0 24px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 15px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(255, 133, 162, 0.3);
  transition: all 0.3s ease-in-out;
  animation: float 3s ease-in-out infinite;
  animation-play-state: paused;
}

.send-button:hover:not(:disabled) {
  background-color: var(--primary-dark);
  box-shadow: 0 5px 15px rgba(255, 133, 162, 0.4);
  transform: translateY(-2px);
  animation-play-state: running;
}

.send-button:active:not(:disabled) {
  transform: scale(0.95);
}

.send-button:disabled {
  background-color: #FFD6DC;
  box-shadow: none;
  animation: none;
}
</style>